/**
 * Copyright (c) 2021 EdgerOS Team.
 * All rights reserved.
 * 
 * Detailed license information can be found in the LICENSE file.
 * 
 * Author       : Fu Wenhao <fuwenhao@acoinfo.com>
 * Date         : 2022-02-10 09:56:42
 * LastEditors  : Fu Wenhao <fuwenhao@acoinfo.com>
 * LastEditTime : 2022-02-17 17:06:05
 */
const sddc = require('../lib/node-sddc');

// 创建SDDC Client
let sddcClient = sddc({
  edgerosIP: '192.168.128.1',
  edgerosPort: 6800, // 680 无须主动上报
  //report
  name: 'PC-Node',
  type: 'device',
  excl: false,
  desc: 'PC端 EdgerOS 节点',
  model: '1',
  vendor: 'MRC'
})

// sddc 消息接收
sddcClient.on('message', (buffer, remoteInfo) => {
  let data = JSON.parse(buffer.toString())
  if (data.type === 'message') {
    console.log("接收到普通消息:", data)
  } else if (data.type === "create_connector") {
    createConnector(sddcClient, data.data.port)
  } else {
    console.log('未知数据', data)
  }
})

// 发送消息
sddcClient.sendMessage(JSON.stringify({ name: 'hello' }))

// connector 链接
function createConnector(sddcClient, port) {
  // 创建 createConnector
  let connecter = sddcClient.createConnector(port)

  // 连接成功
  connecter.on('connect', () => {
    // 通过connector 发送消息
    sddcClient.connecterSend("hello EdgerOS");
  })

  // 接收connector 发送的数据
  connecter.on('data', (chunk) => {
    console.log('connecter 数据接收:', chunk.toString())
  })
}



// 自主上报设备信息
function _report(params) {
  setTimeout(() => {
    sddcClient.discoverHandle()
    if (!sddcClient.edgerInfo) {
      _report()
    } else {
      console.log(sddcClient.edgerInfo)
    }
  }, 2000);
}
_report()
